//========================================================================
// *作者：海盗猫  主页：ilplay.com
// *脚本：DownPacked
// *描述：
// *?2021 MYJL . All rights reserved.
//* ======================================================================
using System;
using System.IO;
using UnityEngine;

namespace HDMCode.FrameEditor
{
    public class DownProgress
    {
        public float Maximum;
        public float Value;
    }

    public static class HDMEditorDownload
    {
        public static void DownPackage(string packName,string URL,Action<float> donwer, Action result)
        {
            string directoryPath = System.Environment.CurrentDirectory + $"/HDMLibrary";
            string filePath = $"{directoryPath}/{packName}.zip";

            if (!System.IO.Directory.Exists(directoryPath))
                System.IO.Directory.CreateDirectory(directoryPath);

            if (File.Exists(filePath))
                File.Delete(filePath);

            DownProgress prog = new DownProgress();
            float percent = 0;
            try
            {
                System.Net.HttpWebRequest Myrq = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(URL);
                System.Net.HttpWebResponse myrp = (System.Net.HttpWebResponse)Myrq.GetResponse();
                long totalBytes = myrp.ContentLength;
                if (prog != null)
                {
                    prog.Maximum = (int)totalBytes;
                }
                System.IO.Stream st = myrp.GetResponseStream();
                System.IO.Stream so = new System.IO.FileStream(filePath, System.IO.FileMode.Create);
                long totalDownloadedByte = 0;
                byte[] by = new byte[1024];
                int osize = st.Read(by, 0, (int)by.Length);
                while (osize > 0)
                {
                    totalDownloadedByte = osize + totalDownloadedByte;
                    so.Write(by, 0, osize);
                    if (prog != null)
                        prog.Value = (int)totalDownloadedByte;
                    osize = st.Read(by, 0, (int)by.Length);
                    percent = (float)totalDownloadedByte / (float)totalBytes * 100;
                    donwer.Invoke(percent);
                }
                so.Close();
                st.Close();
                result.Invoke();
            }
            catch (System.Exception error)
            {
                Debug.Log("下载失败：" + error);
                throw;
            }
        }
    }
}


